import { defineStore } from 'pinia'
import { constRoutes, asyncRoutes, anyRoute } from '@/router/routes'
import { ref } from 'vue'
import { getRouterListAPI } from '@/api/login'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

// 过滤当前用户需要展示的异步路由
const filterasyncRoutes = (asyncRoute: any, routes: any) => {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children) {
        item.children = filterasyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

export const useMenuStore = defineStore('Menu', () => {
  const menuRoutes = ref<any[]>([])

  const setRouter = async () => {
    if (!localStorage.getItem('UserInfo')) return
    const userInfo = JSON.parse(localStorage.getItem('UserInfo')!).UserInfo
    if (!userInfo.account) return
    const res = await getRouterListAPI(userInfo.id)
    const userAsyncRoutes = await filterasyncRoutes(cloneDeep(asyncRoutes), res.data)
    ;[...userAsyncRoutes, anyRoute].forEach((route: any) => {
      router.addRoute(route)
    })
    menuRoutes.value = [...constRoutes[0].children!, ...userAsyncRoutes, anyRoute]
  }

  return { menuRoutes, setRouter }
})
